import React from "react";
import {
  Link,
  Route,
  Switch,
  Redirect,
  useHistory,
  useLocation,
} from "react-router-dom";

class Home extends React.Component {
  render() {
    return (
      <>
        <div>home页面</div>
      </>
    );
  }
}

const About = () => {
  return <div>about页面</div>;
};
const Mine = () => {
  return <div>mine页面</div>;
};

const Login = () => {
  const histroy = useHistory();
  const location = useLocation();
  const login = () => {
    // console.log(location);
    // console.log(histroy);
    localStorage.setItem("token", "12345");

    // 编程式导航，histroy对象下面的push/replace/go/goBack
    histroy.push(location.state.from);
  };

  return (
    <div>
      登录页面 - <button onClick={login}>登录</button>
    </div>
  );
};

// 封装的路由鉴权的组件
const Auth = (props) => {
  return (
    <Route
      path={props.path}
      render={() => {
        if (localStorage.getItem("token")) {
          return props.children;
        } else {
          return (
            <Redirect
              from={props.path}
              to={{
                pathname: "/login",
                state: {
                  from: props.path,
                },
              }}
            ></Redirect>
          );
        }
      }}
    ></Route>
  );
};

const App = () => {
  return (
    <>
      <h2>react-router-v5-路由鉴权</h2>
      <ul>
        <li>
          <Link to="/home">首页</Link>
        </li>
        <li>
          <Link to="/about">关于页</Link>
        </li>
        <li>
          <Link to="/mine">我的页</Link>
        </li>
      </ul>

      <hr />

      <Switch>
        <Redirect from="/" to="/home" exact></Redirect>
        <Route path="/home" component={Home}></Route>
        {/* <Route
          path="/about"
          render={() => {
            if (localStorage.getItem("token")) {
              return <About />;
            } else {
              return <Redirect to="/login"></Redirect>;
            }
          }}
        ></Route> */}

        <Auth path="/about">
          <About />
        </Auth>

        {/* <Route path="/mine" component={Mine}></Route> */}

        <Auth path="/mine">
          <Mine />
        </Auth>

        <Route path="/login">
          <Login />
        </Route>
      </Switch>
    </>
  );
};

export default App;
